﻿Public Class ListViewy
   Inherits System.Windows.Forms.UserControl

   Public Items As New ListItems

   Sub New()
      DoubleBuffered = True
   End Sub

   Dim _Size As Size
   Property ImageSize As Drawing.Size
      Get
         Return _Size
      End Get
      Set(ByVal Value As Drawing.Size)
         _Size = Value
         Rearrange()
      End Set
   End Property

   Dim NoUpdate As Boolean

   Sub Rearrange()
      If NoUpdate Then Return
      Dim x As Integer = 0, y As Integer = 0
      For Each Item In Items
         If x + ImageSize.Width > ClientSize.Width Then
            x = 0
            y += ImageSize.Height
         End If
         Item.Bounds = New Rectangle(New Point(x, y), ImageSize)
         x += ImageSize.Width
      Next
      AutoScrollMinSize = New Size(ClientSize.Width, y + ImageSize.Height)
      Invalidate()
   End Sub

   Event PaintItem(ByVal g As Graphics, ByVal Item As Item)
   Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
		MyBase.OnPaint(e)
		Dim R As Rectangle
		e.Graphics.TranslateTransform(0, -VerticalScroll.Value)
		For Each Item In Items
			R = Item.Bounds
			R.Offset(0, -VerticalScroll.Value)
			If R.IntersectsWith(e.ClipRectangle) Then
				RaiseEvent PaintItem(e.Graphics, Item)
			End If
			'Dim R = Item.Bounds
			'e.Graphics.FillRectangle(Brushes.White, R)
			'R.Inflate(-4, -4)
			'e.Graphics.FillEllipse(Brushes.Blue, R)
		Next
		e.Graphics.ResetTransform()
		R = New Rectangle(0, 0, ClientSize.Width, 15)
		If Not e.ClipRectangle.Contains(R) Then Invalidate(R)
		For y = R.Top To R.Bottom - 1
			e.Graphics.DrawLine(Color.Black.Opacity(255 / (+2)).Pen, R.Left, y, R.Right, y)
		Next
	End Sub

   Protected Overrides Sub OnSizeChanged(ByVal e As System.EventArgs)
      MyBase.OnSizeChanged(e)
      Rearrange()
   End Sub

   Sub SelectAll()
      Throw New NotImplementedException
   End Sub

   Sub BeginUpdate()
      NoUpdate = True
   End Sub

   Sub EndUpdate()
      NoUpdate = False
      Rearrange()
   End Sub

   Class ListItems : Inherits List(Of Item)

      Overloads Function Find(ByVal Key As String) As List(Of Item)
         Return (From i In Me Where i.Name = Key).ToList
      End Function

      Shadows Sub Add(ByVal Item As Item)
         MyBase.Add(Item)
      End Sub


   End Class

   Public Class Item

      Property Name As String
      Property Selected As Boolean
      Property Text As Object
      Property Bounds As Rectangle

   End Class

End Class
